<template>
  <div class="chat-history">
    <!-- 头部信息 -->
    <div class="chat-header">
      <div class="chat-title">{{ chatTitle }}</div>
      <div class="chat-subtitle">共 {{ filteredMessageList.length }} 条消息</div>
    </div>
    
    <!-- 消息列表 -->
    <div class="chat-messages" ref="messagesContainer">
      <div v-if="loading" class="loading-container">
        <el-icon class="is-loading">
          <Loading />
        </el-icon>
        <span>加载中...</span>
      </div>
      
      <div v-else-if="filteredMessageList.length === 0" class="empty-container">
        <el-icon><ChatDotRound /></el-icon>
        <span>暂无聊天记录</span>
      </div>
      
      <div v-else class="message-list">
        <div
          v-for="(message, index) in filteredMessageList"
          :key="message.id"
          class="message-item"
          :class="{ 'user-message': message.role === 'user', 'assistant-message': message.role === 'ai' }"
        >
          <!-- 时间分隔 -->
          <div v-if="shouldShowTime(index, filteredMessageList)" class="time-divider">
            {{ formatMessageTime(message.atTime) }}
          </div>
          
          <!-- 消息内容 -->
          <div class="message-wrapper">
            <!-- 头像 -->
            <div class="message-avatar">
              <el-avatar
                v-if="message.role === 'user'"
                :size="36"
                src="/src/assets/imgs/avatar-user.png"
                style="background-color: #409EFF"
              >
                用户
              </el-avatar>
              <el-avatar
                v-else
                :size="36"
                src="/src/assets/imgs/avatar-ai.png"
                style="background-color: #67C23A"
              >
                AI
              </el-avatar>
            </div>
            
            <!-- 消息气泡 -->
            <div class="message-bubble">
              <div class="message-content">
                {{ getMessageContent(message) }}
              </div>
              
              <!-- 文件附件 -->
              <div v-if="message.files && message.files.length > 0" class="message-files">
                <div
                  v-for="(file, fileIndex) in message.files"
                  :key="fileIndex"
                  class="file-item"
                >
                  <!-- 图片文件 -->
                  <div v-if="isImageFile(file)" class="image-file" @click="handleImageClick(file)">
                    <img :src="file" :alt="message.fileNames?.[fileIndex] || `图片${fileIndex + 1}`" />
                    <div class="image-name">{{ message.fileNames?.[fileIndex] || `图片${fileIndex + 1}` }}</div>
                  </div>
                  
                  <!-- 其他文件 -->
                  <div v-else class="other-file" @click="handleFileClick(file, message.fileNames?.[fileIndex])">
                    <el-icon><Document /></el-icon>
                    <span>{{ message.fileNames?.[fileIndex] || `文件${fileIndex + 1}` }}</span>
                  </div>
                </div>
              </div>
              
              <!-- 消息时间 -->
              <div class="message-time">
                {{ formatDetailTime(message.atTime) }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { Loading, ChatDotRound, Document } from '@element-plus/icons-vue'
import { formatDate } from '@/utils/formatTime'
import * as AIChatApi from '@/api/member/aiChat'

interface Props {
  historyId: string
  chatTitle?: string
}

const props = defineProps<Props>()

const loading = ref(true)
const messageList = ref<AIChatApi.ChatDo[]>([])
const messagesContainer = ref<HTMLElement>()

// 过滤掉atTime为null的消息
const filteredMessageList = computed(() => {
  return messageList.value.filter(message => message.atTime !== null)
})

/** 获取消息内容 */
const getMessageContent = (message: AIChatApi.ChatDo) => {
  // 如果是用户消息，直接返回content
  if (message.role === 'user') {
    return message.content || ''
  }
  
  // 如果是AI消息，从chunk中拼接内容
  if (message.role === 'ai' && message.chunk && Array.isArray(message.chunk)) {
    return message.chunk
      .filter(chunk => chunk.content && chunk.status === 'progressing')
      .map(chunk => chunk.content)
      .join('')
  }
  
  return message.content || ''
}

/** 获取聊天记录 */
const getChatHistory = async () => {
  if (!props.historyId) return
  
  loading.value = true
  try {
    const data = await AIChatApi.getChatHistory(props.historyId)
    messageList.value = Array.isArray(data) ? data : []
    
    // 等待DOM更新后滚动到底部
    await nextTick()
    scrollToBottom()
  } catch (error) {
    console.error('获取聊天记录失败:', error)
    messageList.value = []
  } finally {
    loading.value = false
  }
}

/** 滚动到底部 */
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

/** 判断是否显示时间分隔 */
const shouldShowTime = (index: number, list: AIChatApi.ChatDo[]) => {
  if (index === 0) return true
  
  const currentMessage = list[index]
  const prevMessage = list[index - 1]
  
  // 如果当前消息或前一条消息没有时间，不显示时间分隔
  if (!currentMessage.atTime || !prevMessage.atTime) return false
  
  // 处理时间戳为0的情况
  if (currentMessage.atTime === 0 || prevMessage.atTime === 0) return false
  
  // 如果时间戳小于某个值，可能是秒级时间戳，需要转换为毫秒
  const currentTime = currentMessage.atTime < 1000000000000 ? currentMessage.atTime * 1000 : currentMessage.atTime
  const prevTime = prevMessage.atTime < 1000000000000 ? prevMessage.atTime * 1000 : prevMessage.atTime
  
  // 如果两条消息间隔超过5分钟，显示时间
  return Math.abs(currentTime - prevTime) > 5 * 60 * 1000
}

/** 格式化消息时间（用于时间分隔） */
const formatMessageTime = (time: number | null) => {
  if (!time || time === 0) return ''
  // 如果时间戳小于某个值，可能是秒级时间戳，需要转换为毫秒
  const timestamp = time < 1000000000000 ? time * 1000 : time
  const date = new Date(timestamp)
  const now = new Date()
  
  // 如果是今天，只显示时间
  if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }
  
  // 如果是昨天，显示"昨天 HH:mm"
  const yesterday = new Date(now)
  yesterday.setDate(yesterday.getDate() - 1)
  if (date.toDateString() === yesterday.toDateString()) {
    return `昨天 ${date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}`
  }
  
  // 其他情况显示完整日期时间
  return formatDate(date, 'MM-DD HH:mm')
}

/** 格式化详细时间（用于消息气泡） */
const formatDetailTime = (time: number | null) => {
  if (!time || time === 0) return ''
  // 如果时间戳小于某个值，可能是秒级时间戳，需要转换为毫秒
  const timestamp = time < 1000000000000 ? time * 1000 : time
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

/** 判断是否为图片文件 */
const isImageFile = (url: string) => {
  if (!url) return false
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg']
  const lowerUrl = url.toLowerCase()
  return imageExtensions.some(ext => lowerUrl.includes(ext)) || 
         lowerUrl.includes('image') || 
         lowerUrl.match(/\.(jpg|jpeg|png|gif|bmp|webp|svg)(\?|$)/i)
}

/** 处理图片点击 */
const handleImageClick = (imageUrl: string) => {
  // 在新窗口打开图片
  if (imageUrl) {
    window.open(imageUrl, '_blank')
  }
}

/** 处理文件点击 */
const handleFileClick = (fileUrl: string, fileName?: string) => {
  // 这里可以实现文件预览或下载功能
  console.log('点击文件:', fileName, fileUrl)
  // 简单实现：在新窗口打开文件
  if (fileUrl) {
    window.open(fileUrl, '_blank')
  }
}

// 监听historyId变化，重新加载数据
watch(
  () => props.historyId,
  () => {
    if (props.historyId) {
      getChatHistory()
    }
  },
  { immediate: true }
)
</script>

<style lang="scss" scoped>
.chat-history {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f5f5f5;
}

.chat-header {
  padding: 16px 20px;
  background: white;
  border-bottom: 1px solid #ebeef5;
  
  .chat-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 4px;
  }
  
  .chat-subtitle {
    font-size: 12px;
    color: #909399;
  }
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px 0;
  
  .loading-container,
  .empty-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 200px;
    color: #909399;
    
    .el-icon {
      font-size: 48px;
      margin-bottom: 12px;
    }
  }
}

.message-list {
  .time-divider {
    text-align: center;
    margin: 16px 0 8px;
    color: #909399;
    font-size: 12px;
    position: relative;
    
    &::before {
      content: '';
      position: absolute;
      top: 50%;
      left: 20px;
      right: 20px;
      height: 1px;
      background: #e4e7ed;
      z-index: 0;
    }
    
    span {
      background: #f5f5f5;
      padding: 0 12px;
      position: relative;
      z-index: 1;
    }
  }
}

.message-item {
  margin-bottom: 16px;
  
  &.user-message {
    .message-wrapper {
      flex-direction: row-reverse;
      
      .message-bubble {
        background: #409EFF;
        color: white;
        margin-right: 12px;
        margin-left: 60px;
        
        &::before {
          right: -8px;
          left: auto;
          border-left-color: #409EFF;
          border-right-color: transparent;
        }
      }
    }
  }
  
  &.assistant-message {
    .message-wrapper {
      flex-direction: row;
      
      .message-bubble {
        background: white;
        color: #303133;
        margin-left: 12px;
        margin-right: 60px;
        
        &::before {
          left: -8px;
          border-right-color: white;
          border-left-color: transparent;
        }
      }
    }
  }
}

.message-wrapper {
  display: flex;
  align-items: flex-start;
  padding: 0 20px;
}

.message-avatar {
  flex-shrink: 0;
}

.message-bubble {
  position: relative;
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 12px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  
  &::before {
    content: '';
    position: absolute;
    top: 12px;
    width: 0;
    height: 0;
    border: 8px solid transparent;
    border-top-color: transparent;
    border-bottom-color: transparent;
  }
}

.message-content {
  line-height: 1.5;
  word-wrap: break-word;
  white-space: pre-wrap;
  margin-bottom: 8px;
}

.message-files {
  margin-top: 8px;
  
  .file-item {
    margin-bottom: 8px;
    
    .image-file {
      cursor: pointer;
      border-radius: 8px;
      overflow: hidden;
      max-width: 200px;
      background: rgba(0, 0, 0, 0.05);
      transition: transform 0.2s;
      
      &:hover {
        transform: scale(1.02);
        background: rgba(0, 0, 0, 0.1);
      }
      
      img {
        width: 100%;
        height: auto;
        max-height: 150px;
        object-fit: cover;
        display: block;
      }
      
      .image-name {
        padding: 8px;
        font-size: 12px;
        color: #666;
        text-align: center;
        background: rgba(255, 255, 255, 0.9);
      }
    }
    
    .other-file {
      display: flex;
      align-items: center;
      padding: 8px 12px;
      background: rgba(0, 0, 0, 0.05);
      border-radius: 8px;
      cursor: pointer;
      transition: background-color 0.2s;
      
      &:hover {
        background: rgba(0, 0, 0, 0.1);
      }
      
      .el-icon {
        margin-right: 8px;
        font-size: 16px;
      }
      
      span {
        font-size: 14px;
        text-decoration: underline;
      }
    }
  }
}

.message-time {
  font-size: 11px;
  opacity: 0.7;
  text-align: right;
  margin-top: 4px;
}

// 滚动条样式
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
  
  &:hover {
    background: #a8a8a8;
  }
}
</style> 
